package JavaFoundation.myLock.spinlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/*
自旋锁：while循环+compareAndSet();
 */
public class SpinDemo {
    //原子引用线程
    AtomicReference<Thread> atomicReference = new AtomicReference<>();
    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "===com in ");
        while (!atomicReference.compareAndSet(null,thread)){
            System.out.println("自旋**");
        }
        System.out.println(Thread.currentThread().getName() + "===拿到了锁 ");
    }

    public void myUnLock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+"====解锁");
    }

    public static void main(String[] args) {
        SpinDemo spinDemo = new SpinDemo();
        new Thread(()->{
            spinDemo.myLock();
            try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
            spinDemo.myUnLock();
        },"AA").start();

        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        new Thread(()->{
            spinDemo.myLock();
            spinDemo.myUnLock();
        },"BB").start();
    }

}
